package com.chen.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chen.constant.ResultConstant;
import com.chen.context.BaseContext;
import com.chen.exception.*;
import com.chen.mapper.UsersMapper;
import com.chen.pojo.entity.User;
import com.chen.pojo.vo.SystemInfo;
import com.chen.pojo.vo.UserVo;
import com.chen.service.ContactGroupService;
import com.chen.service.ContactMethodsService;
import com.chen.service.ContactPersonService;
import com.chen.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 陈子安
 * @since 2023-11-30
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UsersMapper, User> implements UserService {

    @Autowired
    // 联系人组服务
    private ContactGroupService contactGroupService;
    @Autowired
    // 联系方式服务
    private ContactMethodsService contactMethodsService;
    // 联系人服务
    @Autowired
    private ContactPersonService contactPersonService;

    @Autowired
    private UsersMapper usersMapper;

    @Override
    public UserVo login(User user) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(user.getEmail() != null, User::getEmail, user.getEmail());
        User one = getOne(wrapper);
        // 邮箱不存在
        if (one == null) {
            throw new EmailNotExist(ResultConstant.MSG_NOT_FOUND_USER);
        }
        // 密码错误
        if (!Objects.equals(one.getPassword(), user.getPassword())) {
            throw new PasswordError(ResultConstant.MSG_PASSWORD_ERROR);
        }
        // 处理密码后返回用户信息
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(one, userVo);
        return userVo;
    }

    @Override
    public void logout() {
        Long id = BaseContext.getCurrentId();
        log.info("要被删除的用户{}", id);
        User user = new User();
        user.setId(id);
        System.out.println(user);
        boolean b = removeById(user);
        if (!b) {
            throw new NotLoginError(ResultConstant.MSG_UNAUTHORIZED_ERROR);
        }
    }

    @Override
    public SystemInfo getSystemInfo() {
        // 检查权限
        checkPermission();
        // 获取用户数量
        Long count = lambdaQuery().count();
        log.info("用户的数量{}", count);
        // 获取禁用用户数量
        Long disabledCount = lambdaQuery().eq(User::getDisabled, 1).count();
        log.info("获取禁用用户数量{}", disabledCount);
        // 统计用户组
        Long groupCount = contactGroupService.count();
        log.info("统计用户组{}", disabledCount);
        // 统计联系人
        Long contactCount = contactPersonService.count();
        log.info("统计联系人{}", disabledCount);
        // 统计联系方式
        Long contactMethodRecordCount = contactMethodsService.count();
        log.info("统计联系方式{}", contactMethodRecordCount);

        SystemInfo systemInfo = new SystemInfo();
        systemInfo.setUserCount(count);
        systemInfo.setDisabledUserCount(disabledCount);
        systemInfo.setGroupCount(groupCount);
        systemInfo.setContactCount(contactCount);
        systemInfo.setContactMethodRecordCount(contactMethodRecordCount);
        return systemInfo;
    }

    @Override
    public List<UserVo> getAllUsers() {
        // 检查权限
        checkPermission();
        List<User> list = list();
        return BeanUtil.copyToList(list, UserVo.class);
    }


    @Override
    public UserVo getUserById(Long id) {
        Long currentId = BaseContext.getCurrentId();
        //  查当前的用是不是管理员
        User byId = getById(currentId);


        User user = getById(id);
        if (user == null) {
            throw new NotFoundUserError(ResultConstant.MSG_NOT_FOUND_USER);
        }
        UserVo userVo = new UserVo();

        Integer isAdmin = byId.getIsAdmin();
        // 是管理员可以查询所有用户信息
        if (isAdmin == 1) {
            // 检查权限
            checkPermission();
            // 权限符合
            BeanUtils.copyProperties(user, userVo);
            return userVo;
        }

        //  不是不管理员只能查询自己的信息
        if (!Objects.equals(user.getId(), currentId)) {
            throw new NoPermissionError(ResultConstant.MSG_NO_PERMISSION);
        }

        BeanUtils.copyProperties(user, userVo);
        return userVo;
    }

    @Override
    public UserVo saveUser(User user) {
        // 检查当前用户的权限
        checkPermission();

        boolean flag = save(user);

        User newUser = getById(user.getId());
        return BeanUtil.copyProperties(newUser, UserVo.class);
    }

    @Override
    public UserVo editUserById(User user) {
        Long id = BaseContext.getCurrentId();
        //查询当前的用户的信息
        User byId = getById(id);

        // 要修改的用户信息
        User userById = getById(user.getId());
        if (userById == null) {
            throw new NotFoundUserError(ResultConstant.MSG_NOT_FOUND_USER);
        }
        // 普通用户只能修改自己的信息 并且不能修改isAdmin字段 disabled 字段
        if (byId.getIsAdmin() != 1) {
            if (!userById.getId().equals(id)) {

                throw new NoPermissionError(ResultConstant.MSG_NO_PERMISSION);
            }
            user.setIsAdmin(null);
            user.setDisabled(null);
        }
        boolean b = updateById(user);
        if (!b) {
            throw new RuntimeException(ResultConstant.MSG_UNKNOWN_ERROR);
        }
        return BeanUtil.copyProperties(userById, UserVo.class);
    }

    @Override
    public UserVo disabledUserById(Long id) {
        Long currentId = BaseContext.getCurrentId();
        // 检验权限
        checkPermission();
        // 判断用户是否存在
        User byId = getById(id);
        if (byId == null) {
            throw new NotFoundUserError(ResultConstant.MSG_NOT_FOUND_USER);
        }
        // 管理员不能禁用自己
        if (Objects.equals(currentId, byId.getId())) {
            throw new NotFoundUserError(ResultConstant.MSG_NOT_FOUND_USER);
        }

        // 设置用户为禁用
        LambdaUpdateWrapper<User> wrapper = new LambdaUpdateWrapper<>();
//        wrapper.set(User::getDisabled, LocalDateTime.now()).eq(User::getId, id);
        wrapper.set(User::getDisabledAt, LocalDateTime.now()).set(User::getDisabled, 1).eq(User::getId, id);
        boolean b = update(wrapper);
        if (!b) {
            throw new RuntimeException(ResultConstant.MSG_UNKNOWN_ERROR);
        }
        byId = getById(id);
        return BeanUtil.copyProperties(byId, UserVo.class);
    }

    @Override
    public UserVo enabledUserById(Long id) {
        // 检验权限
        checkPermission();
        User byId = getById(id);
        if (byId == null) {
            throw new NotFoundUserError(ResultConstant.MSG_NOT_FOUND_USER);
        }
        // 启用用户
        LambdaUpdateWrapper<User> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(User::getDisabledAt, null).set(User::getDisabled, 0).eq(User::getId, id);
        boolean b = update(wrapper);
        if (!b) {
            throw new RuntimeException(ResultConstant.MSG_UNKNOWN_ERROR);
        }
        byId = getById(id);
        return BeanUtil.copyProperties(byId, UserVo.class);

    }

    @Override
    public void deleteUserById(Long id) {
        Long currentId = BaseContext.getCurrentId();
        User user = getById(id);
        if (user == null) {
            throw new NotFoundUserError(ResultConstant.MSG_NOT_FOUND_USER);
        }
        // 检验权限
        checkPermission();
        // 不能删除没有禁用的用户
        Integer disabled = user.getDisabled();
        if (disabled == 0) {
            throw new BaseException(ResultConstant.MSG_USER_NOT_DISABLED);
        }
        //
        LocalDateTime disabledAt = user.getDisabledAt();
        // 禁用时间 + 30  > 当前时间，不能删除
        LocalDateTime plusDays = disabledAt.plusDays(30);
        if (plusDays.isBefore(LocalDateTime.now())) {
            throw new BaseException(ResultConstant.MSG_USER_CAN_NOT_DELETE);
        }

        // 管理员不能删除自己
        if (user.getId().equals(currentId)) {
            throw new NotFoundUserError(ResultConstant.MSG_NOT_FOUND_USER);
        }

        // 删除用户
        boolean b = removeById(id);
        // 修改 disabled_at

        if (!b) {
            throw new BaseException(ResultConstant.MSG_UNKNOWN_ERROR);
        }


    }


    // 检查用户权限
    public void checkPermission() {
        Long id = BaseContext.getCurrentId();
        if (id == null) {
            throw new NotLoginError(ResultConstant.MSG_UNAUTHORIZED_ERROR);
        }
        User one = getById(id);
        if (one.getIsAdmin() != 1) {
            throw new NoPermissionError(ResultConstant.MSG_NO_PERMISSION);
        }
    }
}
